package com.lanou3g.demo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ReflectDemo {
    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Goods g = new Goods();
        g.setName("手机");
        g.setPrice(1999);
        g.setUnit("台");

        // 转成Map
        /*
        name=手机
        price=1999
        unit=台
         */

        Map<String, Object> map =
                beanToMap(g);
        System.out.println(map);

        List<Integer> list = new ArrayList<>();
        list.add(2);
//        list.add("dsdf");
        Class<? extends List> clazz = list.getClass();
        Method add = clazz.getMethod("add", Object.class);
        add.invoke(list, "lksjdlfj");

        System.out.println(list);

//        TimeUnit.SECONDS
//        MyTimeUnit.SECOND

        new Thread().start();


    }

    private static Map<String, Object> beanToMap(Object obj) throws IllegalAccessException {
        /*
        1. 根据对象获取Class对象
        2. 根据Class对象获取所有Field
        3. 遍历Field数组, Field的名字就是Map的key, 值就是Map的value
        4. 组合为键值对的形式放入Map
        5. 返回Map对象
         */
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String key = field.getName();
            Object value = field.get(obj);
            map.put(key, value);
        }

        return map;
    }

    public static class Goods{
        private String name;
        private float price;
        private String unit;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public float getPrice() {
            return price;
        }

        public void setPrice(float price) {
            this.price = price;
        }

        public String getUnit() {
            return unit;
        }

        public void setUnit(String unit) {
            this.unit = unit;
        }
    }
}
